package com.java.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.java.po.Student;
import com.java.service.LogService;
import com.java.service.StudentService;
import com.java.util.EmailUtil;
import com.java.util.LogUtil;
import com.java.util.MD5Util;
import com.java.util.MultipartFileImageUtil;

@Controller
@RequestMapping("/student")
public class StudentController {

	@Autowired
	private StudentService studentService;

	@Autowired
	private LogService logService;

	// 全局变量
	LogUtil logUtil = new LogUtil();
	MultipartFileImageUtil FileImageUtil = new MultipartFileImageUtil();

	/**
	 * 报到登录界面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(@RequestParam(name = "out", defaultValue = "") String out, HttpServletRequest request) {
		// 退出登陆
		if (out.length() != 0) {
			request.getSession().invalidate(); // 杀死所有session
			return "redirect:login";
		}
		return "login";

	}

	@RequestMapping(value = "/loginAndregister", method = RequestMethod.GET)
	public String loginAndregister() {
		// 退出登陆
		return "loginAndregister";

	}

	/**
	 * 登录界面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login2", method = RequestMethod.GET)
	public String login2() {

		return "views/login2";

	}

	/**
	 * 报到首页界面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index() {

		return "views/index";

	}

	/**
	 * 报道提交
	 * 
	 * @param username
	 * @param studentid
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/tlogin", method = RequestMethod.POST)
	public String tlogin(@RequestParam("username") String username, @RequestParam("studentid") String studentid,
			ModelMap map, HttpServletRequest request) {
		String login = "login";
		try {
			if (username.length() != username.trim().length()) {
				map.put("type", "error");
				map.put("msg", "请输入正确的用户名，首部或者尾部存在空格");
				return "login";
			}
			if (username == null || username.length() == 0) {
				map.put("type", "error");
				map.put("msg", "用户名不能为空！");
				return login;
			}
			Student student = studentService.findByNameAndStuId(username, Integer.valueOf(studentid), null);
			if (student == null) {
				map.put("type", "error");
				map.put("msg", "用户不存在！或者学号有误。");
				return login;
			}
			if (student.getState() == 0) {
				map.put("type", "error");
				map.put("msg", "该用户已被禁用，请联系管理员！");
				logService.insertLog(username, logUtil.getLOGIN(), logUtil.getERROR());
				return login;
			}
			request.getSession().setAttribute("student", student);
			if (student.getPassword() == null || student.getPassword().trim().length() == 0) {
				map.put("type", "register");
				map.put("msg", "请完善你的个人信息！");
				logService.insertLog(username, logUtil.getLOGIN(), logUtil.getSUCCESS());
				return "views/register";
			} else {
				map.put("type", "success");
				map.put("msg", "你已经报到过，无需再注册，请使用密码进入！");
			}
		} catch (Exception e) {
			// TODO: handle exception
			map.put("type", "error");
			map.put("msg", "发生未知错误！请联系管理员");
			e.printStackTrace();
		}

		return login;

	}

	/**
	 * 报道与注册提交
	 * 
	 * @param username
	 * @param studentid
	 * @param map
	 * @return
	 */
//	@RequestParam(name = "username") String username,
//	@RequestParam(name = "studentid") String studentid,
//	@RequestParam(name = "password", defaultValue = "") String password,
//	@RequestParam(name = "address", defaultValue = "") String address,
//	@RequestParam(name = "qq", defaultValue = "") String qq,
//	@RequestParam(name = "phone", defaultValue = "") String phone
	@RequestMapping(value = "/tloginAndregister", method = RequestMethod.POST)
	public String tloginAndregister(Student student, @RequestParam("vcode") String vcode,
			@RequestParam("date") String date, @RequestParam("file") MultipartFile file, HttpServletRequest request,
			ModelMap map) {
		System.out.println(student);
		String login = "loginAndregister";
		try {
			// 报到
			if (student.getUsername().length() != student.getUsername().trim().length()) {
				map.put("type", "error");
				map.put("msg", "请输入正确的用户名，首部或者尾部存在空格");
				return "login";
			}
			if (student.getUsername() == null || student.getUsername().length() == 0) {
				map.put("type", "error");
				map.put("msg", "用户名不能为空！");
				return login;
			}
			Student stu = studentService.findByNameAndStuId(student.getUsername(), student.getStudentid(), null);
			if (stu == null) {
				map.put("type", "error");
				map.put("msg", "用户不存在！或者学号有误。");
				return login;
			}
			if (student.getPassword().length() == 0 && stu.getBirthdate() == null) {
				Object attribute = request.getSession().getAttribute("accountLoginCpacha");
				if (attribute == null) {
					map.put("type", "error");
					map.put("msg", "验证码过期，请刷新！");
					return login;
				}
				if (!vcode.equalsIgnoreCase(attribute.toString())) {
					map.put("type", "error");
					map.put("msg", "验证码错误！");
					return login;
				}
				if (stu.getState() == 0) {
					map.put("type", "error");
					map.put("msg", "该用户已被禁用，请联系管理员！");
					logService.insertLog(stu.getUsername(), logUtil.getLOGIN(), logUtil.getERROR());
					return login;
				}
				request.getSession().setAttribute("student", stu);
				map.put("type", "register");
				map.put("msg", "请完善你的个人信息！");
				logService.insertLog(student.getUsername(), logUtil.getLOGIN() + "转" + logUtil.getREGISTER(),
						logUtil.getSUCCESS());
			} else {// 注册
				if (stu.getBirthdate() != null) {
					map.put("type", "login");
					map.put("msg", "你已经报到过，无需再注册，请使用密码进入！");
					return login;
				}
				if (student.getPassword().length() == 0) {
					map.put("type", "register");
					map.put("msg", "请输入密码！");
					return login;
				}
				String fileImage = FileImageUtil.File(file, request, "/images/head", "achievement_gurenl.png");
				stu.setImages(fileImage);// 图片路径存入数据库
				stu.setPassword(MD5Util.md5Password(student.getPassword()));
				stu.setSex(student.getSex());
				stu.setBirthdate(new SimpleDateFormat("yyyy-MM-dd").parse(date));// 字符串转时间
				stu.setPhone(student.getPhone());
				stu.setAddress(student.getAddress());
				stu.setQq(student.getQq());
				stu.setReporttotime(new Date());// 获取本地时间
				studentService.updateStudentById(stu);// 修改
				logService.insertLog(student.getUsername(), logUtil.getREGISTER(), logUtil.getSUCCESS());
				map.put("type", "success");
				map.put("msg", "欢迎进入新生报到系统。");
			}
		} catch (Exception e) {
			// TODO: handle exception
			map.put("type", "error");
			map.put("msg", "发生未知错误！请联系管理员");
			e.printStackTrace();
		}
		return login;

	}

	/**
	 * 登陆提交3
	 * 
	 * @param username
	 * @param studentid
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/tlogin3", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> tlogin3(@RequestParam(name = "username2", defaultValue = "") String username,
			@RequestParam(name = "studentid2", defaultValue = "") String studentid,
			@RequestParam(name = "password2", defaultValue = "") String password,
			@RequestParam(name = "vcode2", defaultValue = "") String vcode, HttpServletRequest request) {
		Map<String, String> retMap = new HashMap<String, String>();
//		System.out.println(username + studentid);
		try {
			if (username.length() != username.trim().length()) {
				retMap.put("type", "error");
				retMap.put("msg", "请输入正确的用户名，首部或者尾部存在空格");
				return retMap;
			}
			if (username == null || username.length() == 0) {
				retMap.put("type", "error");
				retMap.put("msg", "用户名不能为空！");
				return retMap;
			}
			if (password == null || password.trim().length() == 0) {
				retMap.put("type", "error");
				retMap.put("msg", "密码不能为空！");
				return retMap;
			}
			Object attribute = request.getSession().getAttribute("accountLoginCpacha");
			if (attribute == null) {
				retMap.put("type", "error");
				retMap.put("msg", "验证码过期，请刷新！");
				return retMap;
			}
			if (!vcode.equalsIgnoreCase(attribute.toString())) {
				retMap.put("type", "error");
				retMap.put("msg", "验证码错误！");
				return retMap;
			}
			Student stu = studentService.findByNameAndStuId(username, Integer.valueOf(studentid), null);
			if (stu == null) {
				retMap.put("type", "error");
				retMap.put("msg", "用户名不存在！或者密码有误。");
				return retMap;
			}
			if (stu.getPassword() == null || stu.getPassword().trim().length() == 0) {
				retMap.put("type", "register");
				retMap.put("msg", "请完善你的个人信息！");
				logService.insertLog(stu.getUsername(), logUtil.getLOGIN() + "转" + logUtil.getREGISTER(),
						logUtil.getSUCCESS());
				return retMap;
			}
			Student student = studentService.findByNameAndStuId(username, Integer.valueOf(studentid),
					MD5Util.md5Password(password));
			if (student == null) {
				retMap.put("type", "error");
				retMap.put("msg", "用户不存在！或者密码有误。");
				return retMap;
			}
			if (student.getState() == 0) {
				retMap.put("type", "error");
				retMap.put("msg", "该用户已被禁用，请联系管理员！");
				logService.insertLog(username, logUtil.getLOGIN(), logUtil.getERROR());
				return retMap;
			}
			request.getSession().setAttribute("student", student);
			retMap.put("type", "success");
			retMap.put("msg", "欢迎进入学生报到系统！");
			logService.insertLog(username, logUtil.getLOGIN(), logUtil.getSUCCESS());
		} catch (Exception e) {
			// TODO: handle exception
			retMap.put("type", "error");
			retMap.put("msg", "发生未知错误！请联系管理员");
			e.printStackTrace();
		}

		return retMap;

	}

	/**
	 * 登陆提交2
	 * 
	 * @param username
	 * @param studentid
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/tlogin2", method = RequestMethod.POST)
	public String tlogin2(@RequestParam("username") String username, @RequestParam("studentid") String studentid,
			@RequestParam("password") String password, ModelMap map, HttpServletRequest request) {
		String login = "views/login2";
		try {
			if (username.length() != username.trim().length()) {
				map.put("type", "error");
				map.put("msg", "请输入正确的用户名，首部或者尾部存在空格");
				return "login";
			}
			if (username == null || username.length() == 0) {
				map.put("type", "error");
				map.put("msg", "用户名不能为空！");
				return login;
			}
			if (password == null || password.length() == 0) {
				map.put("type", "error");
				map.put("msg", "用户名不能为空！");
				return login;
			}
			Student student = studentService.findByNameAndStuId(username, Integer.valueOf(studentid),
					MD5Util.md5Password(password));
			if (student == null) {
				map.put("type", "error");
				map.put("msg", "用户不存在！或者密码有误。");
				return login;
			}
			if (student.getState() == 0) {
				map.put("type", "error");
				map.put("msg", "该用户已被禁用，请联系管理员！");
				logService.insertLog(username, logUtil.getLOGIN(), logUtil.getERROR());
				return login;
			}
			request.getSession().setAttribute("student", student);
			if (student.getPassword() == null || student.getPassword().trim().length() == 0) {
				map.put("msg", "请完善你的个人信息！");
				logService.insertLog(username, logUtil.getLOGIN(), logUtil.getSUCCESS());
				return "views/register";
			}
			map.put("type", "success");
			map.put("msg", "欢迎进入学生报到系统！");
			logService.insertLog(username, logUtil.getLOGIN(), logUtil.getSUCCESS());
		} catch (Exception e) {
			// TODO: handle exception
			map.put("type", "error");
			map.put("msg", "发生未知错误！请联系管理员");
			e.printStackTrace();
		}

		return login;

	}

	/**
	 * 注册（修改）提交
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "register", method = RequestMethod.POST)
	private String register(Student student, @RequestParam("date") String date,
			@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
		try {
			String fileImage = FileImageUtil.File(file, request, "/images/head", "achievement_gurenl.png");
			student.setImages(fileImage);
			student.setBirthdate(new SimpleDateFormat("yyyy-MM-dd").parse(date));// 字符串转时间
			student.setPassword(MD5Util.md5Password(student.getPassword()));
			student.setReporttotime(new Date());// 获取本地时间
			studentService.updateStudentById(student);
			logService.insertLog(student.getUsername(), logUtil.getREGISTER(), logUtil.getSUCCESS());

		} catch (Exception e) {
			// TODO: handle exception
			logService.insertLog(student.getUsername(), logUtil.getREGISTER(), logUtil.getERROR());
			e.printStackTrace();
		}
		return "views/index";

	}

	/**
	 * 忘记密码信息提交
	 * 
	 * @param account
	 * @return
	 */
	@RequestMapping(value = "/czpad", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> resetpassword(
			@RequestParam(name = "NameAndStudentid", defaultValue = "") String NameAndStudentid,
			@RequestParam(name = "Email", defaultValue = "") String Email, HttpServletRequest request) {
		Map<String, String> retMap = new HashMap<String, String>();
		try {
			// 验证是否存在‘#’并且只有一个
			if (NameAndStudentid.indexOf('#') > -1
					&& (NameAndStudentid.indexOf('#') == NameAndStudentid.lastIndexOf('#'))) {
				// 取各段值
				String[] buff = NameAndStudentid.split("#");
				Student findByNameAndStuId = studentService.findByNameAndStuId(buff[0], Integer.parseInt(buff[1]),
						null);
				if (Email.length() == 0) {
					if (findByNameAndStuId == null) {
						retMap.put("type", "error");
						retMap.put("msg", "用户不存在，请重新填写！");
						return retMap;
					}
					if (findByNameAndStuId.getPassword().length() == 0) {
						retMap.put("type", "error");
						retMap.put("msg", "用户未报到，请完成注册！");
						return retMap;
					}
					retMap.put("type", "success");
				} else {
					// 正则表达邮箱格式
					String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
					Pattern p = Pattern.compile(regEx1);
					Matcher m = p.matcher(Email);
					if (!m.matches()) {
						retMap.put("type", "error");
						retMap.put("msg", "邮箱输入格式有误，请重新填写！");
						return retMap;
					}
				}

			} else {
				retMap.put("type", "error");
				retMap.put("msg", "输入格式有误，请重新填写！");
				return retMap;
			}
			// 随机产生一个6位混合密码
			if (Email.length() != 0) {
				String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
				Random random = new Random();
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < 6; i++) {
					int number = random.nextInt(62);
					sb.append(str.charAt(number));
				}
				String[] buff = NameAndStudentid.split("#");
				Student student = studentService.findByNameAndStuId(null, Integer.parseInt(buff[1]), null);
				student.setPassword(MD5Util.md5Password(sb.toString()));
				if (studentService.updateStudentById(student) <= 0) {
					retMap.put("type", "error");
					retMap.put("msg", "修改失败，请联系管理员！");
					logUtil.setDowhere("进行了密码重置");
					logService.insertLog(buff[0] + "," + buff[1], logUtil.getDowhere(), logUtil.getERROR());
					return retMap;
				}
				// 发送邮箱
				EmailUtil se = new EmailUtil();
				se.doSendHtmlEmail("新生报到系统重置密码", "您的密码重置为：" + sb.toString() + ",为账号安全尽快修改改密码。", Email);
				retMap.put("type", "success");
				retMap.put("msg", "重置成功，请通过邮箱查收！");
				logUtil.setDowhere("进行了密码重置");
				logService.insertLog("(" + buff[0] + "," + buff[1] + ")", logUtil.getDowhere(), logUtil.getSUCCESS());
			}
		} catch (Exception e) {
			// TODO: handle exception
			retMap.put("type", "error");
			retMap.put("msg", "发生未知错误！请联系管理员");
			e.printStackTrace();
		}

		return retMap;

	}

}
